package com.lisa.auto.service.c3.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.lisa.auto.entity.c3.model.Device;
import com.lisa.auto.entity.c3.requst.DeviceBindingRequest;
import com.lisa.auto.entity.c3.requst.DeviceCreateRequest;
import com.lisa.auto.entity.c3.requst.DevicePageRequest;
import com.lisa.auto.enums.C3UrlEnum;
import com.lisa.auto.mapper.c3.DeviceMapper;
import com.lisa.auto.service.c3.DeviceService;
import com.lisa.auto.util.basic.BaseException;
import com.lisa.auto.util.basic.BaseResponse;
import demo.C3ApiDemo;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 设备信息表 服务实现类
 * </p>
 *
 * @author hxh
 * @since 2019-12-24
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements DeviceService {

    private static final Logger LOGGER = LoggerFactory.getLogger(DeviceServiceImpl.class);

    @Value("${c3.url}")
    private String c3url;
    @Value("${c3.appKey}")
    private String appKey;
    @Value("${c3.secretKey}")
    private String secretKey;

    @Override
    public Page<Device> getDevicesList(Page<Device> page) {
        Map<String, Object> condition = page.getCondition();
        EntityWrapper<Device> ew = new EntityWrapper();
        List<Device> devicesList = baseMapper.getDevicesList(ew, page);
        page.setRecords(devicesList);
        return page;
    }

    public List<Device> queryDevicePageList() {
        try {
            String url = c3url + C3UrlEnum.DEVICEPAGEURL.getUrl();
            DevicePageRequest request = new DevicePageRequest();
            request.setAppKey(appKey);
            request.setBindingStatus(true);
            request.setDeviceNo("");
            request.setDeviceType("GPS,TBOX,ADAS_DSM,OBD,VIDEO");
            request.setCurPage(1);
            request.setPageSize(100);
            String requstJson = JSON.toJSONString(request);
            String result = C3ApiDemo.get(url, requstJson, secretKey);
            if (StringUtils.isNotBlank(result)) {
                BaseResponse<Device> baseResponse = JSONObject.parseObject(result, BaseResponse.class);
                if (!baseResponse.isReturnSuccess()) {
                    throw new BaseException("新增设备失败:" + baseResponse.getReturnErrMsg());
                }
                addDevice(baseResponse.getData());
            }
        } catch (Exception e) {
            LOGGER.error("DeviceServiceImpl.createDeviceToC3 ERROR {}", e.getMessage());
            throw new BaseException(e.getMessage());
        }
        return null;
    }

    @Override
    public void addDevice(Device device) {
        if (StringUtils.isEmpty(device.getDeviceNo())) {
            throw new BaseException("设备ID不能为空");
        }
        if (StringUtils.isEmpty(device.getGateWayNo())) {
            throw new BaseException("网关编码不能为空");
        }
        if (StringUtils.isEmpty(device.getManufactureNo())) {
            throw new BaseException("厂商不能为空");
        }
        //查询该设备是否已存在，存在就提示，不存在就新增
        EntityWrapper<Device> ew = new EntityWrapper<>();
        ew.eq("device_no", device.getDeviceNo());
        List<Device> devices = baseMapper.selectList(ew);
        if (devices != null && !devices.isEmpty()) {
            throw new BaseException("设备ID已存在");
        } else {
            baseMapper.insert(device);
        }
    }

    /**
     * 新增设备推C3
     *
     * @param device
     */
    @Override
    public void createDeviceToC3(Device device) {
        try {
            String url = c3url + C3UrlEnum.DEVICESURL.getUrl();
            DeviceCreateRequest request = new DeviceCreateRequest();
            BeanUtils.copyProperties(device, request);
            request.setAppKey(appKey);
            String requstJson = JSON.toJSONString(request);
            String result = C3ApiDemo.post(url, requstJson, secretKey);
            if (StringUtils.isNotBlank(result)) {
                BaseResponse<Device> baseResponse = JSONObject.parseObject(result, BaseResponse.class);
                if (!baseResponse.isReturnSuccess()) {
                    throw new BaseException("新增设备失败:" + baseResponse.getReturnErrMsg());
                }
                addDevice(baseResponse.getData());
            }
        } catch (Exception e) {
            LOGGER.error("DeviceServiceImpl.createDeviceToC3 ERROR {}", e.getMessage());
            throw new BaseException(e.getMessage());
        }
    }

    @Override
    public Device getDeviceDetailFromC3(String no) {
        if (StringUtils.isEmpty(no)) {
            throw new BaseException("设备编号不能为空");
        }
        try {
            String url = c3url + C3UrlEnum.DEVICESURL.getUrl();
            DeviceCreateRequest request = new DeviceCreateRequest();
            request.setAppKey(appKey);
            request.setNo(no);
            String requstJson = JSON.toJSONString(request);
            String result = C3ApiDemo.get(url, requstJson, secretKey);
            if (StringUtils.isNotBlank(result)) {
                BaseResponse<Device> baseResponse = JSONObject.parseObject(result, BaseResponse.class);
                if (!baseResponse.isReturnSuccess()) {
                    throw new BaseException("获取设备详情失败:" + baseResponse.getReturnErrMsg());
                }
                return baseResponse.getData();
            }
        } catch (Exception e) {
            LOGGER.error("DeviceServiceImpl.getDeviceDetailFromC3 ERROR {}", e.getMessage());
            throw new BaseException(e.getMessage());
        }
        return null;
    }

    @Override
    public void updateDeviceToC3(Device device) {
        if (Objects.isNull(device)) {
            throw new BaseException("参数不能为空");
        }
        if (StringUtils.isEmpty(device.getDeviceNo())) {
            throw new BaseException("设备编号不能为空");
        }
        try {
            String url = c3url + C3UrlEnum.DEVICESURL.getUrl();
            DeviceCreateRequest request = new DeviceCreateRequest();
            BeanUtils.copyProperties(device, request);
            request.setAppKey(appKey);
            String requstJson = JSON.toJSONString(request);
            String result = C3ApiDemo.put(url, requstJson, secretKey);
            if (StringUtils.isNotBlank(result)) {
                BaseResponse<Device> baseResponse = JSONObject.parseObject(result, BaseResponse.class);
                if (!baseResponse.isReturnSuccess()) {
                    throw new BaseException("更新设备失败:" + baseResponse.getReturnErrMsg());
                }
                updateDevice(device);
            }
        } catch (Exception e) {
            LOGGER.error("DeviceServiceImpl.updateDeviceToC3 ERROR {}", e.getMessage());
            throw new BaseException(e.getMessage());
        }
    }

    @Override
    public void updateDevice(Device device) {
        if (StringUtils.isEmpty(device.getDeviceNo())) {
            throw new BaseException("设备ID不能为空");
        }
        if (StringUtils.isEmpty(device.getManufactureNo())) {
            throw new BaseException("厂商不能为空");
        }
        //查询该设备是否已存在，存在就更新，不存在就新增
        EntityWrapper<Device> ew = new EntityWrapper<>();
        ew.eq("device_no", device.getDeviceNo());
        List<Device> devices = baseMapper.selectList(ew);
        if (devices != null && !devices.isEmpty()) {
            baseMapper.update(device, ew);
        } else {
            baseMapper.insert(device);
        }
    }

    @Override
    public void deleteDeviceToC3(String nos) {
        if (StringUtils.isEmpty(nos)) {
            throw new BaseException("参数为空");
        }
        try {
            String url = c3url + C3UrlEnum.DEVICESURL.getUrl();
            DeviceCreateRequest request = new DeviceCreateRequest();
            request.setNo(nos);
            request.setAppKey(appKey);
            String requstJson = JSON.toJSONString(request);
            String result = C3ApiDemo.delete(url, requstJson, secretKey);
            if (StringUtils.isNotBlank(result)) {
                BaseResponse<Device> baseResponse = JSONObject.parseObject(result, BaseResponse.class);
                if (!baseResponse.isReturnSuccess()) {
                    throw new BaseException("删除设备失败:" + baseResponse.getReturnErrMsg());
                }
                deleteDevice(nos);
            }
        } catch (Exception e) {
            LOGGER.error("DeviceServiceImpl.deleteDeviceToC3 ERROR {}", e.getMessage());
            throw new BaseException(e.getMessage());
        }
    }

    @Override
    public void deleteDevice(String nos) {
        String[] strings = nos.split(",");
        //查询该设备是否已存在，存在就更新，不存在就新增
        EntityWrapper<Device> ew = new EntityWrapper<>();
        ew.in("no", strings);
        baseMapper.delete(ew);
    }

    @Override
    public void bindingDevice(Map<String, Object> map) {
        if (map.isEmpty()) {
            throw new BaseException("参数为空");
        }
        if (!map.containsKey("noList")) {
            throw new BaseException("需要绑定的设备编号为空");
        }
        if (!map.containsKey("vin")) {
            throw new BaseException("需要绑定的车架号为空");
        }
        List<String> noList = (List<String>) map.get("noList");
        String vin = (String) map.get("vin");
        if (bindingDeviceToData(noList, vin)) throw new BaseException("绑定失败");

        new Thread(() -> {
            LOGGER.info("绑定设备推送C3开始---------------");
            try {
                bindingDeviceToC3(noList, vin);
            } catch (Exception e) {
                LOGGER.error("绑定设备推送C3失败---------------");
            }
            LOGGER.info("绑定设备推送C3结束---------------");
        }).start();

    }

    private void bindingDeviceToC3(List<String> noList, String vin) {
        try {
            String url = c3url + C3UrlEnum.BINDINGDEVICEURL.getUrl();
            DeviceBindingRequest request = new DeviceBindingRequest();
            request.getBody().setNoLis(noList);
            request.getBody().setVin(vin);
            request.setAppKey(appKey);
            String requstJson = JSON.toJSONString(request);
            String result = C3ApiDemo.post(url, requstJson, secretKey);
            if (StringUtils.isNotBlank(result)) {
                BaseResponse baseResponse = JSONObject.parseObject(result, BaseResponse.class);
                if (!baseResponse.isReturnSuccess()) {
                    throw new BaseException("绑定设备失败:" + baseResponse.getReturnErrMsg());
                }
            }
        } catch (Exception e) {
            LOGGER.error("DeviceServiceImpl.bindingDeviceToC3 ERROR {}", e.getMessage());
            throw new BaseException(e.getMessage());
        }
    }

    private boolean bindingDeviceToData(List<String> noList, String vin) {
        Wrapper<Device> ew = new EntityWrapper<>();
        ew.in("no", noList);
        Device device = new Device();
        device.setBindingStatus(1);
        device.setBindingTime(new Date());
        device.setVin(vin);
        return baseMapper.update(device, ew) == 1;
    }


}
